extends Node2D
class_name BaseWeapon

@onready var projectile_manager: Node = $"../../../ProjectileManager"


@export var weapon_name = "基础武器"
@export var damage = 1
@export var attack_speed = 1.0  # 每秒攻击次数
@export var projectile_scene: PackedScene
@export var attack_range = 500.0  # 攻击范围
@export var max_level = 8
@export var knockback = 10.0  # 击退力度

var level = 1
var cooldown = 0.0
var player = null
var enemy_manager = null

func _ready():
	player = get_parent().get_parent()  # 武器 -> Weapons -> Player
	enemy_manager = player.get_node("../EnemyManager")
	update_stats()

func update(delta):
	cooldown -= delta
	
	# 如果冷却完成，尝试攻击
	if cooldown <= 0:
		attack()
		cooldown = 1.0 / attack_speed

func attack():
	
	# 基础武器的攻击实现，子类可以重写此方法
	var targets = find_targets()
	if targets.size() > 0:
		# 选择第一个目标并攻击
		fire_at(targets[0])

func find_targets():
	# 查找范围内的敌人
	var targets = []
	
	
	# 获取所有敌人节点
	var enemies = get_tree().get_nodes_in_group("enemy_hitbox")
	
	for enemy in enemies:
		var distance = player.global_position.distance_to(enemy.global_position)
		if distance <= attack_range:
			targets.append(enemy)
	
	# 按距离排序
	targets.sort_custom(func(a, b): 
		return player.global_position.distance_to(a.global_position) < player.global_position.distance_to(b.global_position)
	)
	
	return targets

func fire_at(target):
	if projectile_scene:
		var projectile = projectile_scene.instantiate()
		projectile_manager.add_child(projectile)
		projectile.global_position = global_position
		
		# 设置发射方向
		var direction = (target.global_position - global_position).normalized()
		projectile.set_up(direction)
		
		# 设置伤害
		if projectile.has_method("set_damage"):
			projectile.set_damage(damage)
		
		# 设置击退
		if projectile.has_method("set_knockback"):
			projectile.set_knockback(knockback)

func level_up():
	if level < max_level:
		level += 1
		update_stats()
		return true
	return false

func update_stats():
	# 根据等级更新武器属性
	# 这是一个基本实现，子类可以重写
	damage = int(damage * (1 + 0.5 * (level - 1)))
	attack_speed = attack_speed * (1 + 0.1 * (level - 1))
	knockback = knockback * (1 + 0.1 * (level - 1))

func get_level_up_description():
	# 返回升级描述，用于UI显示
	var next_damage = int(damage * (1 + 0.5))
	var next_attack_speed = attack_speed * (1 + 0.1)
	var next_knockback = knockback * (1 + 0.1)
	return "升级 %s 到 Lv%d\n伤害: %d -> %d\n攻击速度: %.1f -> %.1f\n击退: %.1f -> %.1f" % [
		weapon_name, level + 1, damage, next_damage, attack_speed, next_attack_speed, knockback, next_knockback
	]

# 基础升级方法，子类可以重写
func apply_upgrade(upgrade_id: String):
	print("基础武器不支持升级：", upgrade_id)

# 通用的属性升级方法，子类可以调用
func upgrade_property(property_name: String, upgrade_rate: float):
	match property_name:
		"damage":
			damage = int(damage * (1.0 + upgrade_rate))
		"attack_speed":
			attack_speed *= (1.0 + upgrade_rate)
		"knockback":
			knockback *= (1.0 + upgrade_rate)
		"attack_range":
			attack_range *= (1.0 + upgrade_rate)
		_:
			print("未知的属性：", property_name) 
